const { API_OK } = require('../../utils/setting')
const wxRequest = require('../../utils/request').wxRequest()
const { goodsList } = require('../../api/goods')

Page({
  data: {
    loading: false,
    title: '汇声艺术中心',
    subTitle: '平凡大众的艺术人生',
    banner: [],
    modules: [{}]
  },
  onLoad() {
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#000000'
    })
  },
  onShow() {
    wx.showLoading({ title: '拼命加载中' })
    this.setData({ loading: true })
    this.getHomeData()
    this.getOnSale()
  },
  onShareAppMessage() {},
  /**
   * 跳转到模块页面
   */
  goTargetPage({ currentTarget }) {
    // console.log(currentTarget)
    let url = currentTarget.dataset.url
    // let params = url.match(/\?type=(\w+)/)
    url += url.includes('?') ? `&image=${currentTarget.dataset.image}` : `?image=${currentTarget.dataset.image}`
    // params && (params[1] === 'periphery')
      // ? wx.navigateTo({ url: `/pages/category/category?type=periphery` })
      // : wx.navigateTo({ url })
    wx.navigateTo({ url })
  },
  /**
   * 获取首页数据
   */
  getHomeData() {
    wx.showLoading({ title: '拼命加载中', mask: true })
    wxRequest.get({
      url: '/api/Index/index',
      callback: wx.hideLoading
    })
      .then(res => {
        console.log(res.code === API_OK)
        if (res.code === API_OK) {
          this.setData({
            loading: false,
            modules: res.data.data.map(item => {
              return {
                id: item.id,
                mode: item.position === 1 ? 'right-padding-30' : item.position === 2 ? 'left-padding-30' : '',
                image: item.images,
                title: item.title,
                sub: item.en_title,
                describe: item.desc,
                link: item.page,
              }
            })
          })
        }
      })
      .catch(err => {
        console.warn(err)
        this.setData({ loading: false })
      })
  },
  /**
   * 获取正在发售的轮播
   */
  async getOnSale() {
    try {
      const res = await goodsList({
        data: { type: 1, is_new: 1, p: 1, per_page: 5 }
      })
      // console.log(res)
      if (res.code === API_OK) {
        this.setData({
          banner: res.data.list.data.map(item => {
            return {
              id: item.goods_id,
              image: item.image && item.image.length && item.image[0].file_path
            }
          })
        })
      }
    } catch(err) {
      console.warn(err)
    }
  }
})
